// CardSwipe 

#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#include<conio.h>
#include<stdio.h>

#include"CS_Animations.h"
#include"CS_Global.h"
#include"CS_Logic.h"
#include"CS_Screen.h"

#define TITLE "       CardSwipe      "

unsigned char gameBoard[16];

void resetGame(void)
{
	initializeGame();

	clrscr();

	displayCredits(SCREEN_LEFT, SCREEN_TOP);

	(void)textcolor(COLOR_BLACK);
	stringToTop(getCenterX(TITLE), SCREEN_HEIGHT - 1u, TITLE, 100);

	drawPlayfield(SCREEN_LEFT, SCREEN_TOP);

	displaySelector(SCREEN_LEFT, SCREEN_TOP, false);

	pointToPlayer(SCREEN_LEFT, SCREEN_TOP, currentPlayer, true);
}

void main(void)
{
	unsigned char key;
	unsigned int seed;
	bool isWinner = false;
	unsigned char result[23];

	result[0] = '\0';

	(void)bgcolor(COLOR_WHITE);
	(void)bordercolor(COLOR_WHITE);

	resetGame();

	while(true)
	{
		++seed;
		if(seed == 0xFFFF) seed = 0;

		if(kbhit())
		{
			key = cgetc();

			switch(key)
			{
			case CH_CURS_DOWN: case CH_CURS_RIGHT:
				moveSelectorRight(SCREEN_LEFT, SCREEN_TOP);
				break;

			case CH_CURS_UP: case CH_CURS_LEFT:
				moveSelectorLeft(SCREEN_LEFT, SCREEN_TOP);
				break;

			case 'r': case 'R': case CH_SPACE:
				srand(seed);
				currentDieSide = rand() % DIE_SIZE;
				rollDie(SCREEN_LEFT + 2, SCREEN_TOP + 11, currentDieSide, DIE_SIDES);
				isWinner = processRoll();
				displayPlayerTray(SCREEN_LEFT, SCREEN_TOP, currentPlayer);
				if(isWinner)
				{
					sprintf(result, "  Player %d Wins (%2d)   ", currentPlayer + 1, calculateScore(currentPlayer));
					(void)textcolor(COLOR_RED);
					stringToTop(getCenterX(result), 22, result, 100);
					cgetc();
					resetGame();
				}
				else
				{
					pointToPlayer(SCREEN_LEFT, SCREEN_TOP, currentPlayer, false);
					++currentPlayer;
					if(currentPlayer == numberOfPlayers) currentPlayer = 0;
					pointToPlayer(SCREEN_LEFT, SCREEN_TOP, currentPlayer, true);
					waitForNextPlayer(SCREEN_LEFT, SCREEN_TOP);
					fillPlayField(SCREEN_LEFT, SCREEN_TOP);
				}
				break;

			case CH_F1:
				resetGame();
				break;

			case CH_F2:
				++numberOfPlayers;
				if(numberOfPlayers > 4) 
				{
					numberOfPlayers = 1;
				}
				resetGame();
				break;
			}
		}
	}
}